package com.atguigu.demo.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.FileInputStream;
import java.io.IOException;

@Controller
public class Controller05Download {

    @Resource
    private ServletContext servletContext;

    @RequestMapping("/do/file/download")
    public ResponseEntity doFileDownload() throws IOException {

        FileInputStream fileInputStream = null;

        try {
            // 一、构建响应体数据
            // 1、创建输入流对象，读取要下载的文件
            String fileVirtualPath = "/images/good.jpg";
            String realPath = servletContext.getRealPath(fileVirtualPath);
            fileInputStream = new FileInputStream(realPath);

            // 2、把文件通过输入流读取到字节数组中，这个字节数组用来作为响应体
            byte[] bytes = new byte[fileInputStream.available()];

            fileInputStream.read(bytes);

            // 二、构建响应消息头
            // 创建 MultiValueMap 类型的对象，用来封装响应消息头
            MultiValueMap<String, String> headers = new HttpHeaders();

            // 传入响应消息体的名称和值
            headers.add("Content-Disposition", "attachment;filename=happy.jpg");

            // 三、构建 ResponseEntity 对象，代表整个响应
            // 创建 ResponseEntity 对象：需要三个参数：响应体、响应消息体、响应状态码
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }

}
